/**********************************************************
 * AdminLoginInterceptor.java
 * Created by ankur
 * Last modified Date: Aug 26, 2008 8:30:56 AM by ankur
 * Version : 0.1
 * Copyright (c) 2008 - 2008 cyberThink Infotech Pvt. Ltd., All rights reserved.
 **********************************************************/

package com.printeverywhere.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.printeverywhere.dto.Admin;
import com.printeverywhere.util.AttributeConstants;
import static com.printeverywhere.util.AttributeConstants.*;
/**
 * The Class AdminLoginInterceptor.
 */
public class AdminLoginInterceptor extends AbstractInterceptor implements
		StrutsStatics {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;
	
	/** The logger. */
	private static Logger logger = Logger.getLogger(AdminLoginInterceptor.class);
	
	/* (non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	public String intercept(ActionInvocation invocation) throws Exception {
		logger.info("Starting synchronized Admin Login interceptor to check Admin Object in Session".intern());
		synchronized (this) {
			// Get the action context from the invocation so we can access the
			// HttpServletRequest and HttpSession objects.
			final ActionContext context = invocation.getInvocationContext();
			HttpServletRequest request = (HttpServletRequest) context.get(HTTP_REQUEST);
			HttpSession session = request.getSession(true);
			// Is there a "user" object stored in the user's HttpSession?
			Admin user = (Admin) session.getAttribute(AttributeConstants.ADMIN);
			if (user == null) {
				// The user has not logged in yet.
				// Is the user attempting to log in right now?
				String url = request.getRequestURL().toString();
				boolean loginAttempt = url.contains(ADMIN_INDEX);
				if(!loginAttempt)loginAttempt = url.contains(ADMIN_DOLOGIN.intern());
				if (loginAttempt) { // The user is
					// attempting to log in.
					logger.info("invoking Proxy ".intern() + invocation.getProxy().getActionName());
					return invocation.invoke();
				}

				// Either the login attempt failed or the user hasn't tried to
				// login yet,
				// and we need to send the login form.
				logger.info("Returning to Login Page".intern());
				return ActionSupport.LOGIN;
			} else {
				return invocation.invoke();
			}
		}
	}
}